package com.le.tester.book.concurrentchallenge.atomicnoblocking15;

import com.le.tester.imooc.ccmouse.common.Node;

import java.util.concurrent.atomic.AtomicReference;

/**
 * createTime：2025-05-26 9:47
 * description：使用Treiber算法构造的非阻塞栈
 */
public class ConcurrentStack<T> {

    AtomicReference<Node<T>> top = new AtomicReference<>();

    public void push(T item) {
        Node<T> newNode = new Node<>(item);
        Node<T> oldHead;
        do {
            oldHead = top.get();
            newNode.next = oldHead;
        } while (!top.compareAndSet(oldHead, newNode));
    }

    public T pop() {
        Node<T> oldHead;
        Node<T> newHead;
        do {
            oldHead = top.get();
            if (oldHead == null) {
                return null;
            }
            newHead = oldHead.next;
        } while (!top.compareAndSet(oldHead, newHead));
        return oldHead.item;
    }

    private static class Node<T> {
        public final T item;

        public Node<T> next;

        public Node(T item) {
            this.item = item;
        }
    }
}
